#include "idxBuilder.h"

static int qsort_compare(const void *s1, const void *s2)
{
  offset_t *t1 = (offset_t *) s1;
  offset_t *t2 = (offset_t *) s2;

  if(t1->texttype > t2->texttype) return 1;
  else if(t1->texttype < t2->texttype) return -1;
  else {
    if(t1->offset > t2->offset) return 1;
    else if(t1->offset < t2->offset) return -1;
    else return 0;
  }
}

void IdxBuilder::build_idx_info(link_list* plink) {
  m_head.num_idx = plink->num_node;
  m_head.num_off = plink->num_off;
  m_head.tsign   = plink->tsign;

  m_index = (idx_index_t*)malloc(m_head.num_idx * sizeof(idx_index_t));
  assert(m_index);
  m_count = (idx_count_t*)malloc(m_head.num_idx * sizeof(idx_count_t));
  assert(m_count);
  m_offset = (offset_t*)malloc(m_head.num_off * sizeof(offset_t));
  assert(m_offset);

  link_node* pnode = plink->head;
  uint32_t idx_id = 0;
  uint32_t off_offset = 0;

  while(1) {
    m_index[idx_id].id = pnode->id;
    m_index[idx_id].weight = pnode->weight;

    m_count[idx_id].off = off_offset;
    m_count[idx_id].num = pnode->num_off;

    for(int i = 0 ; i < pnode->num_off ; ++i) {
      m_offset[off_offset] = pnode->off[i];
      off_offset++;
    }

    qsort(&m_offset[m_count[idx_id].off], pnode->num_off, sizeof(offset_t), qsort_compare);

    pnode = pnode->next;
    idx_id++;
    if(pnode == NULL) {
      //finish
      assert(idx_id == m_head.num_idx);
      assert(off_offset == m_head.num_off);
      break;
    }
  }
}

void IdxBuilder::dump_idx_info(FILE* fp) {
  assert(fp);
  uint32_t ret;

  ret = fwrite(&m_head, sizeof(idx_head_t), 1, fp);
  assert(ret == 1);

  ret = fwrite(m_index, sizeof(idx_index_t) , m_head.num_idx, fp);
  assert(ret == m_head.num_idx);

  ret = fwrite(m_count, sizeof(idx_count_t), m_head.num_idx, fp);
  assert(ret == m_head.num_idx);

  ret = fwrite(m_offset, sizeof(offset_t), m_head.num_off, fp);
  assert(ret == m_head.num_off);
}

void IdxBuilder::free_idx_info() {
  if(m_index)free(m_index);m_index = NULL;
  if(m_count)free(m_count);m_count = NULL;
  if(m_offset)free(m_offset);m_offset = NULL;
}
